<?php

namespace Jammiest\SwigeCore\Kernel;

use Symfony\Component\Console\Application;
use App\Services\CommandService;
use Jammiest\SwigeCore\Tools\Path;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Finder\Finder;

class ConsoleKernel
{
    /**
     * 框启动命令
     */
    protected array $commands = [
        // 服务器管理
        \Jammiest\SwigeCore\Console\Commands\Server\StartCommand::class,
        \Jammiest\SwigeCore\Console\Commands\Server\StopCommand::class,
        \Jammiest\SwigeCore\Console\Commands\Server\RestartCommand::class,
        \Jammiest\SwigeCore\Console\Commands\Server\StatusCommand::class,
        \Jammiest\SwigeCore\Console\Commands\Server\HealthCheckCommand::class,

        // 缓存管理
        \Jammiest\SwigeCore\Console\Commands\Cache\ClearCommand::class,
        \Jammiest\SwigeCore\Console\Commands\Cache\ConfigCommand::class,
        \Jammiest\SwigeCore\Console\Commands\Cache\RouteCommand::class,
    ];


    public function __construct(private ContainerInterface $container)
    {

    }

    public function registerCommands(Application $application): void
    {
        foreach ($this->getCommands() as $commandClass) {
            $application->add($this->container->get($commandClass));
        }
    }


    public function getCommands(): array
    {
        return array_merge(
            $this->commands,
            $this->getDiscoveredCommands()
        );
    }

    private function getDiscoveredCommands(): array
    {
        $commands = [];
        $finder = new Finder();
        $consolePath =  Path::getPathByNamespace('App\\Console\\Commands');
        $finder->files()->in($consolePath)->name('*Command.php');

        foreach ($finder as $file) {
            $className = str_replace(
                ['/', '.php'],
                ['\\', ''],
                'App\\Console\\Commands\\' . $file->getRelativePathname()
            );
            if (is_subclass_of($className, Command::class)) {
                $commands[] = $className;
            }
        }

        return $commands;
    }
}
